package uscdb.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import uscdb.dao.ProductDaoI;
import uscdb.dao.VersionDaoI;
import uscdb.model.Tlogicfile;
import uscdb.model.Tproduct;
import uscdb.model.Tversion;
import uscdb.pageModel.DataGrid;
import uscdb.pageModel.Json;
import uscdb.pageModel.Lversion;
import uscdb.pageModel.PageHelper;
import uscdb.service.VersionServiceI;
import uscdb.util.StringUtil.StringUtil;

@Service
public class VersionServiceImpl implements VersionServiceI {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(VersionServiceImpl.class);

	@Autowired
	private VersionDaoI versionDao;

	@Autowired
	private ProductDaoI productDao;

	@Override
	public Json add(Lversion lversion) {
		Json json = new Json();
		try {
			if (!StringUtil.isEmpty(lversion.getProductName())) {
				Tproduct tproduct = productDao.getByName(lversion.getProductName());
				if (null != tproduct) {
					lversion.setId(UUID.randomUUID().toString());
					Tversion tversion = new Tversion();
					BeanUtils.copyProperties(lversion, tversion);
					tversion.setTproduct(tproduct);
					versionDao.save(tversion);
					json.setSuccess(true);
					json.setMsg("添加成功");
				} else {
					json.setMsg("版本关联的产品[" + lversion.getProductName() + "]不存在");
				}
			} else {
				json.setMsg("版本必须关联一个产品");
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return json;

	}

	@Override
	public Json edit(Lversion lversion) {
		Json json = new Json();
		if (!StringUtil.isEmpty(lversion.getProductName())) {
			// 找出原来的版本信息
			Tversion tversion = versionDao.get(Tversion.class, lversion.getId());
			Tproduct tproduct = tversion.getTproduct();
			// 对比之前版本信息对应的 产品 与 传过来的是否一致;一致则只更新版本信息；
			if (lversion.getProductName().equals(tproduct.getName())) {
				BeanUtils.copyProperties(lversion, tversion);
			} else {
				// 如果不一致先查询修改后的记录是否存在，存在即冲突，不允许返回失败；
				Tproduct tproductNew = productDao.getByName(lversion.getProductName());
				if (null != tproductNew) {
					Set<Tversion> tversionFromtproductNew = tproductNew.getTversionSet();
					for (Tversion t : tversionFromtproductNew) {
						if (t.getName().equals(lversion.getName())) {
							json.setMsg("该版本[" + lversion.getName() + "]在[" + tproductNew.getName() + "]产品下重复!");
							return json;
						}
					}
				} else {
					json.setMsg("该产品[" + lversion.getProductName() + "]不存在!");
					return json;
				}
				// 不存在才先删除旧信息再插入新信息
				Tversion tversionNew = new Tversion();
				lversion.setId(UUID.randomUUID().toString());
				BeanUtils.copyProperties(lversion, tversionNew);
				versionDao.delete(tversion);
				tversionNew.setTproduct(tproduct);
				versionDao.save(tversionNew);
				json.setSuccess(true);
				json.setMsg("修改成功！");
			}
		} else {
			json.setMsg("版本必须关联一个产品");
		}
		return json;
	}

	@Override
	public Json delete(String ids) {
		Json json = new Json();
		List<Tversion> tversionList = new ArrayList<>();
		for (String id : ids.split(",")) {
			Tversion tversion = versionDao.get(Tversion.class,id);
			// 保存需要删除的版本集合
			tversionList.add(tversion);
			Set<Tlogicfile> tlogicfileSet = tversion.getTlogicfileSet();
			if (null != tlogicfileSet && tlogicfileSet.size() > 0) {
				json.setMsg("该版本[" + tversion.getName() + "]下还有逻辑文件，不能被删除");
				return json;
			}
		}
		for (Tversion tversion : tversionList) {
			versionDao.delete(tversion);
		}
		json.setMsg("删除成功");
		json.setSuccess(true);
		return json;
	}

	@Override
	public DataGrid dataGrid(Lversion lversion, PageHelper ph) {
		DataGrid dg = new DataGrid();
		List<Lversion> lversionList = new ArrayList<>();
		List<Tversion> tversionList = new ArrayList<>();
		Map<String, Object> params = new HashMap<>();
		String hql = "from Tversion t ";
		tversionList = versionDao.find(hql + orderHql(ph), params, ph.getPage(), ph.getRows());
		for (Tversion tversion : tversionList) {
			Lversion lversion2Page = new Lversion();
			BeanUtils.copyProperties(tversion, lversion2Page);
			// 获取版本对应的产品名
			lversion2Page.setProductName(tversion.getTproduct().getName());
			lversionList.add(lversion2Page);

		}
		dg.setTotal(versionDao.count("select count(*) " + hql, params));
		dg.setRows(lversionList);
		return dg;

	}

	/**
	 * 排序函数
	 * 
	 * @param ph
	 *            分页对象
	 * @return
	 */
	private String orderHql(PageHelper ph) {
		String orderString = "";
		if (ph.getSort() != null && ph.getOrder() != null) {
			orderString = " order by t." + ph.getSort() + " " + ph.getOrder();
		}
		return orderString;
	}

	@Override
	public Lversion get(String id) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("id", id);
		String hql = "from Tversion t where t.id = :id";
		Tversion tversion = versionDao.get(hql, params);
		Lversion lversion = new Lversion();
		BeanUtils.copyProperties(tversion, lversion);
		return lversion;
	}

	@Override
	public List<Lversion> versionCombobox(String productName) {
		if (null == productName || StringUtil.isEmpty(productName)) {
			productName = "";
		}
		Map<String, Object> params = new HashMap<>();
		params.put("productName", productName.trim().toUpperCase());
		String hql = "from Tversion t where t.tproduct.name = :productName order by t.name";
		List<Tversion> tversionList = versionDao.find(hql, params, 1, 20);
		List<Lversion> versionList = new ArrayList<>();
		if (null != tversionList && tversionList.size() > 0) {
			for (Tversion tversion : tversionList) {
				Lversion lversion = new Lversion();
				lversion.setName(tversion.getName());
				versionList.add(lversion);
			}
		}
		return versionList;
	}

}
